<template>
  <div class="tool-detail-container" v-loading="loading">
    <template v-if="!loading && tool">
      <div class="tool-header">
        <div class="tool-info">
          <h1 class="tool-title">{{ tool.name }}</h1>
          <div class="tool-meta">
            <el-tag size="small" type="info">{{ getCategoryName(tool.categoryId) }}</el-tag>
            <span class="tool-views">
              <el-icon><View /></el-icon>
              {{ tool.views }} 次使用
            </span>
          </div>
          <p class="tool-desc">{{ tool.description }}</p>
        </div>
      </div>

      <el-divider />

      <div class="tool-content">
        <!-- 文本格式化工具示例 -->
        <template v-if="tool.id === 1">
          <div class="text-format-tool">
            <div class="tool-options">
              <el-select v-model="formatType" placeholder="选择格式化类型">
                <el-option label="JSON" value="json" />
                <el-option label="XML" value="xml" />
                <el-option label="HTML" value="html" />
              </el-select>
              <el-button type="primary" @click="formatText">格式化</el-button>
              <el-button @click="clearText">清空</el-button>
              <el-button @click="copyText">复制结果</el-button>
            </div>
            <div class="text-areas">
              <div class="input-area">
                <h3>输入文本</h3>
                <el-input
                  v-model="inputText"
                  type="textarea"
                  :rows="15"
                  placeholder="请输入需要格式化的文本..."
                />
              </div>
              <div class="output-area">
                <h3>格式化结果</h3>
                <el-input
                  v-model="outputText"
                  type="textarea"
                  :rows="15"
                  readonly
                  placeholder="格式化后的文本将显示在这里..."
                />
              </div>
            </div>
          </div>
        </template>

        <!-- 其他工具类型可以在这里添加 -->
        <template v-else>
          <el-empty description="该工具正在开发中，敬请期待..." />
        </template>
      </div>

      <el-divider />

      <div class="tool-related">
        <h2>相关工具</h2>
        <div class="related-tools">
          <el-card
            v-for="relatedTool in relatedTools"
            :key="relatedTool.id"
            class="related-tool-card"
            @click="goToToolDetail(relatedTool.id)"
          >
            <div class="related-tool-icon">
              <el-icon><component :is="relatedTool.icon" /></el-icon>
            </div>
            <div class="related-tool-info">
              <h3>{{ relatedTool.name }}</h3>
              <p>{{ relatedTool.description }}</p>
            </div>
          </el-card>
        </div>
      </div>
    </template>

    <el-empty v-else-if="!loading && !tool" description="未找到该工具" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Document, Picture, Calculator, View } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const loading = ref(true)
const tool = ref<any>(null)

// 文本格式化工具相关状态
const formatType = ref('json')
const inputText = ref('')
const outputText = ref('')

// 模拟分类数据
const categories = ref([
  { id: 1, name: '文本工具' },
  { id: 2, name: '图片工具' },
  { id: 3, name: '计算工具' },
  { id: 4, name: '开发工具' },
  { id: 5, name: '日常工具' }
])

// 模拟工具数据
const tools = ref([
  {
    id: 1,
    name: '文本格式化',
    description: '格式化JSON、XML、HTML等文本内容，使其更易于阅读和编辑。支持多种格式化选项，可以自定义缩进、换行等样式。',
    icon: 'Document',
    categoryId: 1,
    views: 1256
  },
  {
    id: 2,
    name: '文本加密解密',
    description: '支持多种加密算法，保护您的文本安全',
    icon: 'Lock',
    categoryId: 1,
    views: 986
  },
  {
    id: 3,
    name: '图片压缩',
    description: '无损压缩图片，减小文件体积',
    icon: 'Picture',
    categoryId: 2,
    views: 2345
  },
  {
    id: 4,
    name: '图片格式转换',
    description: '支持JPG、PNG、GIF等格式互转',
    icon: 'Picture',
    categoryId: 2,
    views: 1789
  }
])

// 获取相关工具
const relatedTools = computed(() => {
  if (!tool.value) return []
  return tools.value
    .filter(t => t.id !== tool.value.id && t.categoryId === tool.value.categoryId)
    .slice(0, 3)
})

// 获取分类名称
const getCategoryName = (categoryId: number) => {
  const category = categories.value.find(c => c.id === categoryId)
  return category ? category.name : '未分类'
}

// 获取工具详情
const getToolDetail = async () => {
  loading.value = true
  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 500))
    const toolId = parseInt(route.params.id as string)
    tool.value = tools.value.find(t => t.id === toolId) || null
  } catch (error) {
    console.error('获取工具详情失败', error)
    tool.value = null
  } finally {
    loading.value = false
  }
}

// 格式化文本
const formatText = () => {
  if (!inputText.value.trim()) {
    ElMessage.warning('请输入需要格式化的文本')
    return
  }

  try {
    if (formatType.value === 'json') {
      // 格式化JSON
      const parsed = JSON.parse(inputText.value)
      outputText.value = JSON.stringify(parsed, null, 2)
    } else if (formatType.value === 'xml') {
      // 简单的XML格式化，实际项目中可能需要更复杂的处理
      outputText.value = inputText.value
        .replace(/></g, '>\n<')
        .replace(/><\/(\w+)>/g, '>\n</$1>')
    } else if (formatType.value === 'html') {
      // 简单的HTML格式化，实际项目中可能需要更复杂的处理
      outputText.value = inputText.value
        .replace(/></g, '>\n<')
        .replace(/><\/(\w+)>/g, '>\n</$1>')
    }
    ElMessage.success('格式化成功')
  } catch (error) {
    console.error('格式化失败', error)
    ElMessage.error(`格式化失败: ${(error as Error).message}`)
  }
}

// 清空文本
const clearText = () => {
  inputText.value = ''
  outputText.value = ''
}

// 复制结果
const copyText = () => {
  if (!outputText.value) {
    ElMessage.warning('没有可复制的内容')
    return
  }

  navigator.clipboard.writeText(outputText.value)
    .then(() => {
      ElMessage.success('复制成功')
    })
    .catch(err => {
      console.error('复制失败', err)
      ElMessage.error('复制失败')
    })
}

// 跳转到工具详情页
const goToToolDetail = (id: number) => {
  if (id === parseInt(route.params.id as string)) return
  router.push(`/tool/${id}`)
}

onMounted(() => {
  getToolDetail()
})
</script>

<style scoped>
.tool-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.tool-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.tool-title {
  font-size: 2rem;
  color: #303133;
  margin: 0 0 10px 0;
}

.tool-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
}

.tool-views {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #909399;
  font-size: 0.9rem;
}

.tool-desc {
  color: #606266;
  font-size: 1rem;
  margin: 0;
  max-width: 800px;
}

.tool-content {
  margin: 30px 0;
}

/* 文本格式化工具样式 */
.text-format-tool {
  width: 100%;
}

.tool-options {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.text-areas {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.input-area,
.output-area {
  flex: 1;
  min-width: 300px;
}

.input-area h3,
.output-area h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

/* 相关工具样式 */
.tool-related h2 {
  font-size: 1.5rem;
  color: #303133;
  margin-bottom: 20px;
}

.related-tools {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.related-tool-card {
  flex: 1;
  min-width: 250px;
  max-width: 350px;
  cursor: pointer;
  transition: transform 0.3s;
  display: flex;
}

.related-tool-card:hover {
  transform: translateY(-5px);
}

.related-tool-icon {
  font-size: 1.5rem;
  color: #409eff;
  margin-right: 15px;
}

.related-tool-info h3 {
  font-size: 1rem;
  margin: 0 0 5px 0;
  color: #303133;
}

.related-tool-info p {
  font-size: 0.9rem;
  color: #606266;
  margin: 0;
}

@media (max-width: 768px) {
  .tool-header {
    flex-direction: column;
  }
  
  .text-areas {
    flex-direction: column;
  }
}
</style> 